package com.bins.charts.pdf;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

public class SplitPdf {

    public static void main(String[] args) throws Exception {
        String file = "D:\\zto\\zto1.pdf";
        String savePath = "D:\\";
        split(file, savePath);
    }

    public static List<Map<String, String>> split(String fileName, String filePath) throws Exception {
        List<Map<String, String>> mapList = new ArrayList<>();
        Document document = null;
        PdfCopy copy = null;
        PdfReader reader = new PdfReader(fileName);
        int n = reader.getNumberOfPages();
        for (int i = 1; i <= n; i++) {
            String perPagePath = splitPage(reader, filePath, i, i);
            HashMap<String, String> map = new HashMap<>();
            map.put("PDF", perPagePath);
            mapList.add(map);
        }
        return mapList;
    }

    private static String splitPage(PdfReader reader, String filePath, Integer from, Integer end) throws DocumentException, IOException {
        Document document;
        PdfCopy copy;
        if (from == 0) {
            from = 1;
        }
        int a = filePath.lastIndexOf("/");
        String staticPath = filePath.substring(0, a);
        String saveFileName = from + "_" + end + ".pdf";
        String saveFilePath = filePath + saveFileName;
        document = new Document(reader.getPageSize(1));
        copy = new PdfCopy(document, new FileOutputStream(saveFilePath));
        document.open();
        for (int j = from; j <= end; j++) {
            document.newPage();
            PdfImportedPage page = copy.getImportedPage(reader, j);
            copy.addPage(page);
        }
        document.close();
        return saveFilePath;
    }
}